# -*- coding: utf-8 -*-

import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import Cookie
import urllib
import urllib2

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

webapp.template.register_template_library('smart_if')
template.register_template_library('django.contrib.markup.templatetags.markup')

from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
from utilities import *
from django.utils import simplejson
from translator import *
from paging import *

from google.appengine.ext.webapp import template

# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    logincontrol = LoginControl()
    access = logincontrol.CheckAccess('admin')
    if access == 1:
      logged = True
    else:
      logged = False

    values = {
      'request': self.request,
      'application_name': 'qstack',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))


class Index(BaseRequestHandler):
  def get(self):
    queryitems = Sello.all()
    queryitems.order('-selloId')
    sellos = queryitems.fetch(20)

    template_values = {
      'sellos': sellos,
    }
    self.generate('index.html', template_values)

class GoogleVerification(BaseRequestHandler):
  def get(self, page = 1):
    template_values = {
    }
    self.generate('googleverification.html', template_values)

class Privacidad(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('politica-privacidad.html', template_values)

class QuienesSomos(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('quienes-somos.html', template_values)

class Enlaces(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('enlaces.html', template_values)

class Contacto(BaseRequestHandler):
  def get(self):
    template_values = {}
    self.generate('contacto.html', template_values)
  def post(self):
    if self.request.get("send") != "" and self.request.get("email") != "":
      name = self.request.get("name")
      email = self.request.get("email")
      message = self.request.get("message")

      # Send an email to shop owners
      mailtosend = mail.EmailMessage(sender="anabelen@gmail.com",subject="Mensaje sellosdefutbol.com de " + name + " - " + email)
      mailtosend.to = "anabelen@gmail.com"
      mailtosend.reply_to = email
      mailtosend.body = message
      try:
        mailtosend.send()
      except:
        p=0

      template_values = {
        'sent': True,
      }
      self.generate('contacto.html', template_values)
    else:
      template_values = {}
      self.generate('contacto.html', template_values)

class SiteMap(BaseRequestHandler):
  def get(self):

    queryitems = Blog.all()
    blogs = queryitems.fetch(500)

    queryitems = Revista.all()
    revistas = queryitems.fetch(500)
    
    queryitems = Video.all()
    videos = queryitems.fetch(500)
    
    queryitems = Libro.all()
    libros = queryitems.fetch(500)
    
    queryitems = Tutorial.all()
    tutoriales = queryitems.fetch(500)

    template_values = {
      'blogs': blogs,
      'revistas': revistas,
      'videos': videos,
      'libros': libros,
      'tutoriales': tutoriales,
    }
    print "Content-Type: text/xml"
    self.generate('sitemap.xml', template_values)

class Sellos(BaseRequestHandler):
  def get(self):

    queryitems = Sello.all()
    queryitems.order('-selloId')
    sellos = queryitems.fetch(500)

    template_values = {
      'sellos': sellos,
    }
    self.generate('sellos.html', template_values)

class SelloPage(BaseRequestHandler):
  def get(self, selloId):

    queryposts = Sello.all()
    queryposts.filter(' selloId = ', int(selloId))
    sellos = queryposts.fetch(1)
    sello = sellos[0]

    template_values = {
      'sello': sello,
    }
    self.generate('sello.html', template_values)

class Favelet(BaseRequestHandler):

  def get(self):
    queryitems = Categoria.all()
    queryitems.order('plural')
    categorias = queryitems.fetch(500)

    queryitems = Tag.all()
    queryitems.order('plural')
    tags = queryitems.fetch(500)

    template_values = {
      'categorias': categorias,
      'tags': tags,
    }
    self.generate('dfavelet.js', template_values)


class CategoriaTag(BaseRequestHandler):
  def get(self, slug):
    
    queryitems = Categoria.all()
    queryitems.filter(' pluralSlug = ', slug)
    items = queryitems.fetch(1)
    
    if len(items) > 0:
      categoria = items[0]
      
      queryitems = Sello.all()
      queryitems.filter(' categoriaSlug = ', slug)
      queryitems.order('-selloId')
      sellos = queryitems.fetch(500)

      template_values = {
        'categoria': categoria,
        'sellos': sellos,
      }
      self.generate('categoria.html', template_values)
    else:
      queryitems = Tag.all()
      queryitems.filter(' pluralSlug = ', slug)
      items = queryitems.fetch(1)
      tag = items[0]
      
      queryitems = Sello.all()
      queryitems.filter(' tagSlug = ', slug)
      queryitems.order('-selloId')
      sellos = queryitems.fetch(500)

      template_values = {
        'tag': tag,
        'sellos': sellos,
      }
      self.generate('tag.html', template_values)


class PatronesCategoriaTag(BaseRequestHandler):
  def get(self, slug):
    
    queryitems = Categoria.all()
    queryitems.filter(' pluralSlug = ', slug)
    items = queryitems.fetch(1)
    
    if len(items) > 0:
      categoriatag = items[0]
      
      queryitems = Sello.all()
      queryitems.filter(' categoriaSlug = ', slug)
      queryitems.order('-selloId')
      sellos = queryitems.fetch(500)

      template_values = {
        'categoriatag': categoriatag,
        'sellos': sellos,
      }
      self.generate('patrones-tag.html', template_values)
    else:
      queryitems = Tag.all()
      queryitems.filter(' pluralSlug = ', slug)
      items = queryitems.fetch(1)
      categoriatag = items[0]
      
      queryitems = Sello.all()
      queryitems.filter(' tagSlug = ', slug)
      queryitems.order('-selloId')
      sellos = queryitems.fetch(500)

      template_values = {
        'categoriatag': categoriatag,
        'sellos': sellos,
      }
      self.generate('patrones-tag.html', template_values)

class SelloImg(BaseRequestHandler):
  def get(self, slug):

    queryposts = Sello.all()
    queryposts.filter(' slug = ', slug)
    sellos = queryposts.fetch(1)

    if len(sellos) > 0:
      sello = sellos[0]
      self.response.headers['Content-Type'] = "image/jpeg"
      self.response.headers['Cache-Control'] = "public, max-age=363600"
      self.response.out.write(sello.bytes_content)
    else:
      self.error(500)
      errorlauncher = ErrorLauncher()
      errorlauncher.Launch(self,404)
      return 1


class SelloImgResized(webapp.RequestHandler):
  def get(self, slug, width, height, action):
    queryposts = Sello.all()
    queryposts.filter(' slug = ', slug)
    sellos = queryposts.fetch(1)

    if len(sellos) > 0:
      myfile = sellos[0]
      if action=='resized':
        if height=='auto':
          content = myfile.bytes_content
          img=images.Image(content)
          originalwidth = float(img.width)
          originalheight = float(img.height)
          resizedwidth = float(width)
          resizedheight = float(float(originalheight*resizedwidth)/originalwidth)
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
        elif width=='auto':
          content = myfile.bytes_content
          img=images.Image(content)
          originalwidth = float(img.width)
          originalheight = float(img.height)
          resizedheight = float(height)
          resizedwidth = float(float(originalwidth*resizedheight)/originalheight)
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
        else:
          content = myfile.bytes_content
          img=images.Image(content)
          resizedwidth=float(width)
          resizedheight=float(height)
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))

        image = images.Image(resizedcontent)
        image.crop(0.0, 0.0, 1.0, 1.0)
        image_data = image.execute_transforms(output_encoding=images.JPEG, quality=100)

        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(image_data)
      elif action=='cropped':
        width=float(width)
        height=float(height)
        content = myfile.bytes_content
        img=images.Image(content)
        originalwidth = float(img.width)
        originalheight = float(img.height)
        resizedwidth = width
        if originalwidth>=originalheight:
          resizedheight = height
          resizedwidth = (originalwidth*resizedheight)/originalheight
        if resizedwidth<=width:
          resizedwidth = width
          resizedheight = (originalheight*resizedwidth)/originalwidth

        resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
        resizedimg=images.Image(resizedcontent)
        originalwidth = resizedimg.width
        originalheight = resizedimg.height
        relativewidth = (width/originalwidth)
        relativeheight = (height/originalheight)
        borderwidth = math.fabs((1 - relativewidth)/2)
        borderheight = math.fabs((1 - relativeheight)/2)
        left_x = borderwidth
        right_x = 1 - borderwidth
        top_y = borderheight
        bottom_y = 1 - borderheight
        #croppedcontent=images.crop(resizedcontent, left_x, top_y, right_x, bottom_y)

        image = images.Image(resizedcontent)
        image.crop(left_x, top_y, right_x, bottom_y)
        image_data = image.execute_transforms(output_encoding=images.JPEG, quality=100)

        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(image_data)
      else:
        image = images.Image(file.bytes_content)
        image.crop(0.0, 0.0, 1.0, 1.0)
        image_data = image.execute_transforms(output_encoding=images.JPEG, quality=100)

        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(image_data)
    else:
      self.error(500)
      errorlauncher = ErrorLauncher()
      errorlauncher.Launch(self,500)
      return 1



class SaveFavelet(BaseRequestHandler):
  def get(self):
    url = urllib.unquote(self.request.get("u"))
    title = urllib.unquote(self.request.get("t"))
    image = urllib.unquote(self.request.get("i"))
    slug = urllib.unquote(self.request.get("s"))
    category = urllib.unquote(self.request.get("c"))
    categorySlug = urllib.unquote(self.request.get("cs"))
    tag = urllib.unquote(self.request.get("ta"))
    tagSlug = urllib.unquote(self.request.get("tas"))
    description = urllib.unquote(self.request.get("d"))

    result = urlfetch.fetch(image)
    content = result.content
    
    img = images.Image(content)

    unasello = Sello()
    unasello.bytes_content = db.Blob(content)
    unasello.width = img.width
    unasello.height = img.height
    unasello.title = title
    unasello.url = url
    unasello.urlimg = image
    unasello.slug = slug
    unasello.tag = tag
    unasello.tagSlug = tagSlug
    unasello.categoria = category
    unasello.categoriaSlug = categorySlug
    unasello.description = description

    queryitem = Sello.all()
    queryitem.order('-selloId')
    items = queryitem.fetch(1)

    if not len(items) > 0:
      lastId = 0
    else:
      lastId = items[0].selloId

    selloId = lastId + 1
    unasello.selloId = selloId

    unasello.put()

    self.response.out.write("Saved!");

def main():
  urlmap = [
            ('/', Index),
            ('/page/(.*)/', Index),
            ('/google03e298e060fd8943.html', GoogleVerification),
            ('/quienes-somos', QuienesSomos),
            ('/contacto', Contacto),
            ('/enlaces', Enlaces),
            ('/save/from_favelet', SaveFavelet),
            ('/sellos', Sellos),
            ('/sello/(.*)/img', SelloImg),
            ('/sello/(.*)/img/(.*)/(.*)/(resized)/', SelloImgResized),
            ('/sello/(.*)/img/(.*)/(.*)/(cropped)/', SelloImgResized),
            ('/sello/(.*)', SelloPage),
            ('/sitemap.xml', SiteMap),
            ('/favelet', Favelet),
            ('/(.*)', CategoriaTag),
           ]

  application = webapp.WSGIApplication(urlmap, debug=_DEBUG)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

